package com.taotao.chisha;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.taotao.chisha.db.DatabaseHelper;
import com.taotao.chisha.entity.Meal;
import com.taotao.chisha.entity.MealLog;
import com.taotao.chisha.util.DateTimeUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {
    private Button btnSee, btnInput, btnFind;
    private View inputView;
    private EditText etName, etVendor;
    private ListView lvHistory;
    private AlertDialog inputAlertDialog, resultAlertDialog;
    private SimpleAdapter adapter;
    private List<Map<String, String>> listData = new ArrayList<Map<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        listData = getHistory();
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter == null) {
            adapter = new SimpleAdapter(this, listData, R.layout.list_item_history,
                    new String[]{"name", "time"},
                    new int[]{R.id.tv_name, R.id.tv_time}
            );
            lvHistory.setAdapter(adapter);
        }
    }

    private AlertDialog getInputAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("录入")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(inputView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        dialogInterface.cancel();
                    }
                })
                .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        String name = etName.getText().toString();
                        String vendor = etVendor.getText().toString();
                        try {
                            Dao<Meal, Integer> mealDao = getHelper().getMealDao();
                            mealDao.create(new Meal(name, vendor));
                            Log.i("gg", "Save: " + name + "--" + vendor);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        dialogInterface.cancel();
                    }
                });
        return builder.create();
    }

    private void initEvent() {
        btnInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputAlertDialog.show();
            }
        });
        btnFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Dao<Meal, Integer> mealDao = getHelper().getMealDao();
                    if (mealDao.countOf() <= 0) {
                        Toast.makeText(MainActivity.this, "先录入美食", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Dao<MealLog, Integer> mealLogDao = getHelper().getMealLogDao();
                    MealLog mealLog = mealLogDao.queryBuilder().orderBy("created_time", false).queryForFirst();
                    String message = "";
                    String title = "";
                    Log.i("gg", "now: " + System.currentTimeMillis());
                    if (mealLog != null
                            && System.currentTimeMillis() - mealLog.createdTime <= 2 * 3600 * 1000) {
                        Log.i("gg", "last time: " + mealLog.createdTime);
                        Meal meal = mealDao.queryForId(mealLog.meal.id);
                        message = "已经决定要吃【" + meal.mealName + "】了~";
                        title = "提示";
                    } else {
                        long count = mealDao.countOf();
                        int randomIndex = (int) (Math.random() * count) + 1;
                        Log.i("gg", "randomIndex: " + randomIndex);
                        Meal meal = mealDao.queryForId(randomIndex);
                        mealLogDao.create(new MealLog(meal));
                        Log.i("gg", "Get: " + meal.mealName + "--" + meal.vendor);
                        message = meal.mealName + "--" + meal.vendor;
                        title = "吃这个";
                    }
                    resultAlertDialog.setTitle(title);
                    resultAlertDialog.setMessage(message);
                    resultAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                    resultAlertDialog.show();

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        btnSee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Dao<Meal, Integer> mealDao = getHelper().getMealDao();
                    List<Meal> meals = mealDao.queryBuilder().orderBy("created_time", false).query();
                    StringBuilder sb = new StringBuilder();
                    for (Meal meal : meals) {
                        sb.append(meal.mealName).append("--").append(meal.vendor).append("\n");
                    }
                    resultAlertDialog.setTitle("已有美食");
                    resultAlertDialog.setMessage(sb.toString());
                    resultAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
                    resultAlertDialog.show();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private List<Map<String, String>> getHistory() {
        try {
            Dao<MealLog, Integer> mealLogDao = getHelper().getMealLogDao();
            Dao<Meal, Integer> mealDao = getHelper().getMealDao();
            List<MealLog> mealLogs = mealLogDao.queryBuilder().orderBy("created_time", false).query();
            for (MealLog mealLog : mealLogs) {
                Meal meal = mealDao.queryForId(mealLog.meal.id);
                Map<String, String> map = new HashMap<String, String>();
                map.put("name", meal.mealName + "--" + meal.vendor);
                map.put("time", DateTimeUtil.getDateString(mealLog.createdTime));
                listData.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return listData;
    }

    private void initView() {
        btnSee = (Button) findViewById(R.id.btn_see);
        btnInput = (Button) findViewById(R.id.btn_input);
        btnFind = (Button) findViewById(R.id.btn_find);
        inputView = ((LayoutInflater) (getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE))).inflate(R.layout.dialog_input, null);
        etName = (EditText) inputView.findViewById(R.id.et_name);
        etVendor = (EditText) inputView.findViewById(R.id.et_vendor);
        lvHistory = (ListView) findViewById(R.id.lv_history);
        if (inputAlertDialog == null) {
            inputAlertDialog = getInputAlertDialog();
        }
        if (resultAlertDialog == null) {
            resultAlertDialog = new AlertDialog.Builder(MainActivity.this).create();
        }
    }
}
